package thread.demo05_3.Condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionDemo2 {
	private Lock lock = new ReentrantLock();
	private Condition conditionA = lock.newCondition();
	private Condition conditionB = lock.newCondition();

	public static void main(String[] args) throws InterruptedException {

		LockConditionDemo2 demo = new LockConditionDemo2();

		new Thread(() -> demo.await(demo.conditionA), "thread1_conditionA").start();
		new Thread(() -> demo.await(demo.conditionB), "thread2_conditionB").start();
		new Thread(() -> demo.signal(demo.conditionA), "thread3_conditionA").start();
		System.out.println("稍等5秒再通知其他的线程！");
		Thread.sleep(5000);
		new Thread(() -> demo.signal(demo.conditionB), "thread4_conditionB").start();
		/**
		 * 从结果可以看出实现了分别通知。因此，我们可以使用Condition进行分组，可以单独的通知某一个分组，另外还可以使用signalAll()方法实现通知某一个分组的所有等待的线程。
		 */
	}

	/**
	 * 等待
	 * 
	 * @param condition
	 */
	private void await(Condition condition) {
		try {
			lock.lock();
			System.out.println("开始等待await！ ThreadName：" + Thread.currentThread().getName());
			condition.await();
			System.out.println("等待await结束！ ThreadName：" + Thread.currentThread().getName());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	/**
	 * 通知
	 * 
	 * @param condition
	 */
	private void signal(Condition condition) {
		lock.lock();
		System.out.println("发送通知signal！ ThreadName：" + Thread.currentThread().getName());
		condition.signal();
		lock.unlock();
	}

}
